package com.autumn.scheduler;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.quartz.CronScheduleBuilder;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerUtils;
import org.quartz.spi.OperableTrigger;

import com.autumn.util.ExceptionUtils;

/**
 * 调度工具
 * 
 * @author 老码农
 *
 *         2018-04-03 12:30:05
 */
public class SchedulerUtils {

	/**
	 * 获取作业调度时间列表
	 * 
	 * @param cronExpression
	 *            cron 表达式
	 * @param numTimes
	 *            时钟数
	 * @return
	 *
	 */
	public static List<Date> getJobFireTimeList(String cronExpression, Date startTime, int numTimes) {
		ExceptionUtils.checkNotNullOrBlank(cronExpression, "cronExpression");
		if (numTimes < 1) {
			ExceptionUtils.throwArgumentOverflowException("numTimes", "运行次数不能小于1");
		}
		try {
			if (startTime == null) {
				startTime = new Date();
			}
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
			String jobKey = UUID.randomUUID().toString().replace("-", "");
			OperableTrigger trigger = (OperableTrigger) TriggerBuilder.newTrigger().withIdentity(jobKey, "test")
					.withSchedule(scheduleBuilder).withDescription("测试").startAt(startTime).build();
			List<Date> dates = TriggerUtils.computeFireTimes(trigger, null, numTimes);
			/*List<Date> results = new ArrayList<>();
			for (Date date : dates) {

			}*/
			return dates;

		} catch (Exception e) {
			throw ExceptionUtils.throwFormatException("cron 格式不正确。");
		}
	}
}
